<?php
	//Database
	require_once $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/database.php';
	require_once $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/profile.php';

	$tab_before = 'profile';
	
	//If profile edited
	if (isset($_SESSION['user']) && isset($_POST['edit'])) {
		//Update
		mysql_query("UPDATE users SET " .
				"password='" . md5($_POST['password']) . "', " .
				"realname='" . $_POST['name'] . "', " .
				"email='" . $_POST['email'] . "', " .
				"avatar_id='" . $_POST['avatar'] . "', " .
				"wall_privilege='" . $_POST['privilege'] . "', " .
				"birth='" . $_POST['birth'] . "', " .
				"gender='" . $_POST['gender'] . "', " .
				"location='" . $_POST['location'] . "' " .
				"WHERE id='" . $_SESSION['user'] . "'");
	}
	
	//Is there any new post
	if (isset($_POST['title']) && isset($_POST['post'])) {
		//Add new post to the database
		mysql_query("INSERT INTO wall_posts (user_id, title, content)
			VALUES('" . $_SESSION['user'] . "','" . $_POST['title'] . "','" . $_POST['post'] . "')") or die(mysql_error());
		$tab_before = 'wall';
	}
	
	//Is there any new comment
	if (isset($_POST['post_id']) && isset($_POST['comment'])) {
		//Add new post to the database
		mysql_query("INSERT INTO wall_comments (user_id, post_id, content)
			VALUES('" . $_SESSION['user'] . "','" . $_POST['post_id'] . "','" . $_POST['comment'] . "')") or die(mysql_error());
		$tab_before = 'wall';
	}

	//Ensure user logged in
	if (isset($_SESSION['user']) && is_numeric($_SESSION['user'])) {
		if ($_SESSION['user'] == $user['id']) {		
			//Delete wall?
			$deleted_wall		= -1;
			$deleted_comments	= array();
			if (isset($_GET['del-wall']))		$deleted_wall = $_GET['del-wall'];
			if (isset($_GET['del-comment']))	$deleted_comments = array($_GET['del-comment']);
			
			//If wall is deleted
			if ($deleted_wall > 0) {
				//set tab
				$tab_before = 'wall';
			
				//Get comments
				$result = mysql_query("SELECT id FROM wall_comments WHERE post_id='" . $deleted_wall . "'");
				$row	= mysql_fetch_array($result);

				//Insert to array
				$deleted_comments = array();
				while ($row) {
					$deleted_comments[] = $row['id'];
					$row = mysql_fetch_array($result);
				}
				
				//Delete wall
				mysql_query("DELETE FROM wall_posts WHERE id='" . $deleted_wall . "'");
			}

			//Delete comments
			foreach ($deleted_comments as $deleted_comment) {
				mysql_query("DELETE FROM wall_comments WHERE id='" . $deleted_comment . "'");
				$tab_before = 'wall';
			}

		} else {
			//Check privilege
			if ($user['wall_privilege'] >= 2) {
				//Find
				$result = mysql_query("SELECT * FROM followers WHERE user_id='" . $user['id'] . "' AND follower_id='" . $_SESSION['user'] . "'");
				if (mysql_num_rows($result) < 1 || $user['wall_privilege'] == 3) {
					header("Location:http://" . $_SERVER['HTTP_HOST'] . '/deviantpic/index.php');
					die();
				}
			}
		}
	} else if ($user['wall_privilege'] > 1) {
		header("Location:http://" . $_SERVER['HTTP_HOST'] . '/deviantpic/index.php');
		die();
	}

	//Check for message send
	if (isset($_POST['thread']) && isset($_POST['receiver']) && isset($_POST['subject']) && isset($_POST['message'])) {
		//set tab
		$tab_before = 'inbox';
		
		//Get subject and message
		$subject = $_POST['subject'];
		$message = $_POST['message'];

		//Get thread
		$thread = $_POST['thread'];
		if ($thread == -1) {
			//Get max thread
			$result	= mysql_query("SELECT MAX(thread) FROM messages") or die(mysql_error());
			$row	= mysql_fetch_row($result);

			//Set thread
			$thread = $row[0] + 1;
		}

		//Add message
		mysql_query("INSERT INTO messages (sender_id, thread, subject, content) VALUES (" . $_SESSION['user'] . "," . $thread . ",'" . $subject . "','" . $message . "')")
			or die(mysql_error());
		$message_id = mysql_insert_id();

		//Get receiver
		$receivers		= array();
		$receivers_name	= $_POST['receiver'];
		$token			= strtok($receivers_name, ",");

		//While there's still a receiver
		while ($token) {
			//Trim whitespace
			$receiver_name = trim($token);

			//Get ID
			$result			= mysql_query("SELECT id FROM users WHERE username='$receiver_name'") or die(mysql_error());
			$row			= mysql_fetch_array($result);
			$receivers[]	= $row['id'];

			//Next
			$token = strtok(",");
		}

		//Add message receivers
		foreach ($receivers as $receiver) {
			mysql_query("INSERT INTO message_receivers (message_id, receiver_id) VALUES (" . $message_id . "," . $receiver . ")");
		}

	}
	
	//check admin action
	$_SESSION['admin_action_ensues'] = null;
	$_SESSION['action_content'] = null;

	if (isset($_POST['reset-pass']) || isset($_POST['block-user']) || isset($_POST['delete-photo'])) {
		//set tab
		$tab_before = 'admin';
		
		$_SESSION['admin_action_ensues'] = TRUE;
		$result = FALSE;

		//check password reset
		if(isset($_POST['reset-pass'])) {
			//reset user password
			$default_pass = md5("deviantpic");
			$result = mysql_query("UPDATE users SET password='. $default_pass .' WHERE id=" . $_POST['reset-pass'])  or die(mysql_error());

			//if success
			if($result==TRUE) {
				$_SESSION['action_content'] = "User password with USERID ". $_POST['reset-pass'] . " has been reseted to default password (deviantpic)";
				$_POST['reset-pass'] = NULL;
			}
		}

		//check user block
		if(isset($_POST['block-user'])) {

			//block user, actually.. delete it. now full-assed
			//delete all wall comments
			$result = mysql_query("DELETE FROM wall_comments WHERE user_id=".$_POST['block-user']) or die(mysql_error());
			//delete all wall post and comment
			$result = mysql_query("DELETE wall_comments,wall_posts FROM wall_comments LEFT JOIN wall_posts ON wall_comments.post_id=wall_posts.id WHERE wall_posts.user_id=".$_POST['block-user']) or die(mysql_error());
			//delete all outbox message
			$result = mysql_query("DELETE FROM messages WHERE sender_id=".$_POST['block-user']) or die(mysql_error());
			//delete inbox message
			$result = mysql_query("DELETE messages,message_receivers FROM messages LEFT JOIN message_receivers ON messages.id=message_receivers.message_id WHERE message_receivers.receiver_id=".$_POST['block-user']) or die(mysql_error());
			//delete follower relationship
			$result = mysql_query("DELETE FROM followers WHERE user_id=".$_POST['block-user']) or die(mysql_error());
			$result = mysql_query("DELETE FROM followers WHERE follower_id=".$_POST['block-user']) or die(mysql_error());
			//delete photo comments
			$result = mysql_query("DELETE FROM photo_comments WHERE user_id=".$_POST['block-user']) or die(mysql_error());
			$result = mysql_query("DELETE photo_comments FROM photo_comments LEFT JOIN tags ON tags.photo_id=photo_comments.photo_id WHERE tags.is_owner=1 AND tags.user_id=".$_POST['block-user']) or die(mysql_error());
			//delete photo ratings
			$result = mysql_query("DELETE FROM photo_ratings WHERE user_id=".$_POST['block-user']) or die(mysql_error());
			$result = mysql_query("DELETE photo_ratings FROM photo_ratings LEFT JOIN tags ON tags.photo_id=photo_ratings.photo_id WHERE tags.is_owner=1 AND tags.user_id=".$_POST['block-user']) or die(mysql_error());
			//delete photo tags relationship
			$result = mysql_query("DELETE FROM tags WHERE is_tagged=1 AND user_id=".$_POST['block-user']) or die(mysql_error());

			//roundabout way to delete photo tags
			$photo_array = array();
			$photo_result = mysql_query("SELECT * FROM tags WHERE is_owner=1 AND user_id=".$_POST['block-user']) or die(mysql_error());
			$photo_row = mysql_fetch_array($photo_result);

			$index = 0;
			$index_max = mysql_num_rows($photo_result);

			while($index<$index_max) {
				$photo_array[]= $photo_row;
				$photo_row = mysql_fetch_array($photo_result);
				$index++;
			}

			foreach ($photo_array as $photo_row) {
				$result = mysql_query("DELETE FROM tags WHERE photo_id=".$photo_row['photo_id']) or die(mysql_error());
			}

			//delete photo and tag ownership
			$result = mysql_query("DELETE photos FROM photos LEFT JOIN tags ON photos.id=tags.photo_id WHERE tags.is_owner=1 AND tags.user_id=".$_POST['block-user']) or die(mysql_error());
			$result = mysql_query("DELETE FROM tags WHERE is_owner=1 AND user_id=".$_POST['block-user']) or die(mysql_error());
			//finally, delete user
			$result = mysql_query("DELETE FROM users WHERE id=".$_POST['block-user']) or die(mysql_error());

			//if success
			if($result==TRUE) {
				$_SESSION['action_content'] = "User with USERID ". $_POST['block-user'] . " has been blocked";
				$_POST['block-user'] = NULL;
			}
		}

		//check delete photo
		if(isset($_POST['delete-photo'])) {
			//delete photo
			$result = mysql_query("DELETE FROM photos WHERE id=".$_POST['delete-photo']) or die(mysql_error());
			$result = mysql_query("DELETE FROM tags WHERE photo_id=".$_POST['delete-photo']) or die(mysql_error());
			$result = mysql_query("DELETE FROM photo_ratings WHERE photo_id=".$_POST['delete-photo']) or die(mysql_error());
			$result = mysql_query("DELETE FROM photo_comments WHERE photo_id=".$_POST['delete-photo']) or die(mysql_error());

			//if success
			if($result==TRUE) {
				$_SESSION['action_content'] = "Photo with ID ". $_POST['delete-photo'] . " with all of its properties (if exist) has been deleted.";
				$_POST['delete-photo'] = NULL;
			}
		}

		//check result
		if ($result=FALSE) $_SESSION['action_content']="There is something's wrong with the command.";
	}
	
	//$url = urlencode("http://milestone.if.itb.ac.id/web/215/13508074/user/profile/");

	//header("Location: https://www.facebook.com/dialog/oauth?client_id=173419782707773&redirect_uri=" . $url . "&scope=publish_stream");

	//Doctype
	require_once $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/doctype.php';

	//get result
	$result = "";

	$callback	= urlencode("http://milestone.if.itb.ac.id/web/215/13508074/index.php");
	$nonce		= md5(uniqid(rand(), true));
	$timestamp	= time();
	$consumer	= "BjblDyfxeWzg2cZBHtac2g";
	$secret		= "OJcd8PxiHNimv27POtxZg0E1CyztshiQXydwjcVpXk&";
	$signature	= "";


	$base = " POST&" . urlencode("https://api.twitter.com/oauth/request_token") . "&";
	$base .= urlencode("oauth_callback") . "%3D" . $callback . "%26";
	$base .= urlencode("oauth_consumer_key") . "%3D" . urlencode($consumer) . "%26";
	$base .= urlencode("oauth_nonce") . "%3D" . urlencode($nonce) . "%26";
	$base .= urlencode("oauth_signature_method") . "%3D" . urlencode("HMAC-SHA1") . "%26";
	$base .= urlencode("oauth_timestamp") . "%3D" . urlencode($timestamp) . "%26";
	$base .= urlencode("oauth_version") . "%3D" . urlencode("1.0");

	$signature = urlencode(hash_hmac("sha1", $base, $secret));

	//echo $base . "<br />";
	//echo $signature . "<br />";

	/*
	header("POST /oauth/request_token HTTP/1.1");
	header("Host: api.twitter.com");
	header("Content-Type: application/x-www-form-urlencoded");
	header("Authorization: OAuth oauth_nonce=\"" . $nonce  . "\", oauth_callback=\"" . $callback . "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" . $timestamp . "\", oauth_consumer_key=\"" . $consumer . "\", oauth_signature=\"" . $signature . "\", oauth_version=\"1.0\"");
	header("Connection: close");*/

	//Create socket connection
	/*$socket = fsockopen("api.twitter.com", 80);
	if ($socket) {
		//Send header
		fputs($socket, "POST /oauth/request_token HTTP/1.1\r\n");
		fputs($socket, "Host: api.twitter.com\r\n");
		fputs($socket, "Content-Type: application/x-www-form-urlencoded\r\n");
		fputs($socket, "Authorization: OAuth oauth_nonce=\"" . $nonce  . "\", oauth_callback=\"" . $callback . "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" . $timestamp . "\", oauth_consumer_key=\"" . $consumer . "\", oauth_signature=\"" . $signature . "\", oauth_version=\"1.0\"");
		//fputs($socket, "Content-Length: 27");
		fputs($socket, "Connection: close\r\n\r\n");
		echo "halo";
		while (!feof($socket)) {
			$result .= fgets($socket);
		}
		echo "2";
	}

	//close socket
	fclose($socket);*/

	echo $result;
?>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>deviantPIC - <?php echo $user['username'] ?>'s Profile</title>
        <script type="text/javascript" src="/deviantpic/script/comments.js"></script>
        <script type="text/javascript" src="/deviantpic/script/profile.js"></script>
		<script type="text/javascript" src="/deviantpic/script/notification.js"></script>
    </head>
    <body onload=<?php echo "check_notification(" . (isset($_SESSION['user']) ? $_SESSION['user'] : -1) . ");changeTab(". "'" . $tab_before . "'". ',' . $user['id'] . ');' ?> >
		
		<!-- Header -->
		<?php require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/header.php';	?>

		<!-- Content -->
		<div id="body">
			<?php
				write_username(isset($_SESSION['user']) ? $_SESSION['user'] : null, "index");
				write_usertabs(isset($_SESSION['user']) ? $_SESSION['user'] : null, 0);
			?>

			<form action="http://api.twitter.com/1/statuses/update.format" method="post"><p>
				<textarea name="status"></textarea>
				<input type="submit" value="submit">
			</p></form>

			<div id="notification">
				<div id="notification-title"></div>
				<div id="notifications" >
					<ul id="notification-list">
					</ul>
				</div>
			</div>
			
			<!-- Contents -->
			<div id="contents">
				
			</div>
			
		</div>

		<!-- Footer -->
		<?php require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/footer.php'; ?>
    </body>
</html>